import {Button, Card, Form, List, message, Modal, Select, Space, Typography} from 'antd';
import React, {useEffect, useState} from 'react';
import {ProColumns} from '@ant-design/pro-table';
import {Report} from './data.d';
import PageContainer from "@ant-design/pro-layout/es/components/PageContainer";
import {EyeOutlined, PlusOutlined} from "@ant-design/icons/lib";
import {list, listForSelect, save} from "@/assets/service/baseService";
import {modulesUrl} from "@/assets/constant/modulesUrl";
import {dateFormat, formSetFieldsValue, hooksSet} from "@/assets/utils/utils";
import {Link} from "react-router-dom";
import {useRequest} from "umi";
import ModalForm from "@/assets/components/modalForm";
import {addSeeNumber} from "@/pages/report/ReportList/service";
import {handleRemove} from "@/assets/components/tableList";
import "./index.css";

const ReportList: React.FC<{}> = () => {
  const [formModalVisible, handleModalVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [modalFormValues] = useState({});
  const [form] = Form.useForm();

  /**
   * 获取数据配置select列表
   */
  const tableConfigSelectList = useRequest(() => listForSelect(modulesUrl.reportTableConfig)).data

  const [reportList, setReportList] = useState<any[]>([]);
  /**
   * 获取报表列表run
   */
  const getReportListRun = useRequest(() => list(modulesUrl.reportReport), {
    manual: true,
    onSuccess: (result) => {
      hooksSet(setReportList, result);
      setLoading(false)
    }
  }).run

  /**
   * 增加查看次数
   */
  const addSeeNumberRun = useRequest((id?: string) => addSeeNumber(id), {
    manual: true,
    onSuccess: (result) => {
      console.log("增加成功")
    }
  }).run

  const columns: ProColumns<Report>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '数据表',
      dataIndex: 'tableConfigId',
      renderFormItem: () => {
        return <Form.Item key={"tableConfigId"} name={"tableConfigId"} label={"数据表"}
                          rules={[{required: true, message: '类型为必填项',},]}>
          <Select placeholder="请选择数据表" options={tableConfigSelectList}></Select>
        </Form.Item>
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: "textarea",
      formItemProps: {
        rules: [
          {
            required: true,
            message: '描述为必填项',
          },
        ],
      },
    },
  ];

  /**
   * 添加/保存节点
   * @param fields
   */
  const handleSave = async () => {
    const hide = message.loading('正在添加');
    try {
      await save(modulesUrl.reportReport, form.getFieldsValue());
      getReportListRun()
      handleModalVisible(false)
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败！');
      return false;
    }
  };

  /**
   * 启动加载
   */
  useEffect(() => {
    // 获取报表列表
    setLoading(true)
    getReportListRun()
  }, []);

  return (
    <PageContainer>
      <div>
        <List<Partial<Report>>
          rowKey="id"
          loading={loading}
          grid={{
            gutter: 16,
            xs: 1,
            sm: 2,
            md: 3,
            lg: 3,
            xl: 4,
            xxl: 4,
          }}
          dataSource={[{}, ...reportList]}
          // @ts-ignore
          renderItem={(report: Report) => {
            if (report && report.id) {
              // 获取表配置ID
              let tableConfigId = report.tableConfigId
              // 获取名称
              let name = report.name
              return (
                <List.Item key={report.id}>
                  <Card
                    title={<span style={{fontWeight: "bold"}}>{report.name}</span>}
                    headStyle={{minHeight:"0px "}}
                    hoverable
                    actions={
                      [
                        // <Link
                        //   to={"/report/report/details/" + tableConfigId + "/" + name + "/" + report.id}
                        //   onClick={() => addSeeNumberRun(report.id)} style={{cursor: "pointer"}}
                        // >
                        //   <a key="option1">查看</a>
                        // </Link>,
                        <a key="option2"
                           onClick={() => {
                             formSetFieldsValue(form, report, "tableConfig.id")
                             handleModalVisible(true)
                           }}
                        >编辑</a>,
                        <a key="option2"
                           onClick={() => {
                             Modal.confirm({
                               title: '删除',
                               content: '确定删除吗？',
                               okText: '确认',
                               cancelText: '取消',
                               onOk: () => handleRemove(report.id, modulesUrl.reportReport, null, () => {
                                 window.location.reload()
                               }),
                             });
                           }}
                        >删除</a>,
                      ]}
                  >
                    <Link to={"/report/report/details/" + tableConfigId + "/" + name + "/" + report.id}
                          onClick={() => addSeeNumberRun(report.id)} style={{cursor: "pointer"}}>
                      <Card.Meta
                        avatar={<img alt="" src={require('@/assets/images/report.png')}
                                     style={{width: "50px"}}/>}
                        // title={<span style={{fontWeight: "bold"}}>{report.name}</span>}
                        description={
                          <Typography.Paragraph style={{color: "rgba(0, 0, 0, 0.45)", height:"70px"}}>
                            <Space direction={"vertical"}>
                              <div>{"创建时间：" + dateFormat(report.createDate, 'YYYY-MM-DD')}</div>
                              <div>{"创建人：" + report.createByUser?.name}</div>
                              <div>
                                <span><EyeOutlined style={{marginRight: "5px"}}/>{report.seeNumber}</span>
                              </div>
                            </Space>
                          </Typography.Paragraph>
                        }
                      />
                    </Link>
                  </Card>
                </List.Item>
              );
            }
            return (
              <List.Item>
                <Button type="dashed" style={{
                  width: '100%',
                  height: '215px',
                  color: '@text-color-secondary',
                  // color: "rgba(0, 0, 0, 0.45)",
                  backgroundColor: '@component-background',
                  borderColor: '@border-color-base'
                }} onClick={() => handleModalVisible(true)}>
                  <PlusOutlined/> 新增报表
                </Button>
              </List.Item>
            );
          }}
        />
      </div>
      <ModalForm columns={columns} form={form} handleSave={handleSave} values={modalFormValues}
                 visible={formModalVisible} onCancel={() => handleModalVisible(false)}/>
    </PageContainer>
  );
}

export default ReportList;
